/**
 * 
 */
package idv.takeshi.software.productline.bookstore.infrastructure.persistence.jpa;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.Validate;
import org.springframework.stereotype.Repository;

import idv.takeshi.software.productline.bookstore.domain.model.book.BookDuplicateException;
import idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryService;
import idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryServiceDuplicateException;
import idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryServiceRepository;

/**
 * A model repository implementation for DeliveryServiceRepository.
 * @author takeshi
 *
 */
@Repository("deliveryServiceRepository")
public class DeliveryServiceRepositoryImpl implements DeliveryServiceRepository {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryServiceRepository#add(idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryService)
	 */
	public void add(DeliveryService deliveryService) throws DeliveryServiceDuplicateException {
		Validate.notNull(deliveryService, "deliveryService shall always not be null");
		try {
			this.entityManager.persist(deliveryService);
		} catch(EntityExistsException  e){
			throw new DeliveryServiceDuplicateException("deliveryService:" + 
					deliveryService.getName() + " is duplicate");
		}
	}

	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryServiceRepository#findById(java.lang.Integer)
	 */
	public DeliveryService findById(Integer id) {
		Validate.notNull(id, "id shall always not be null");
		return this.entityManager.find(DeliveryService.class, id);
	}
	
	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryServiceRepository#update(idv.takeshi.software.productline.bookstore.domain.model.deliveryservice.DeliveryService)
	 */
	public void update(DeliveryService deliveryService){
		Validate.notNull(deliveryService, "deliveryService shall always not be null");
		this.entityManager.merge(deliveryService);
	}

}
